package com.smwish;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class VoteWishServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(VoteWishServlet.class.getName());

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        String wishKey = req.getParameter("key");
        
	    PersistenceManager pm = PMF.get().getPersistenceManager();
                
        Key k = KeyFactory.stringToKey(wishKey);
        
        Wish wish = pm.getObjectById(Wish.class, k);
        wish.incrVotes(user);
        
        try {
            pm.makePersistent(wish);
        } finally {
            pm.close();
        }
        
        //Return the key with votes added.
        resp.setContentType("text/xml");
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");
        resp.setDateHeader("Expires",0);
        PrintWriter out=resp.getWriter();
        out.write(wishKey + "@@@" + wish.getVotes());
        log.warning("Voter response = " + out.toString() );
    }
}